package com.jredu.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class BaseDao {
	private String url = "jdbc:mysql://127.0.0.1:3306/mydb";
	private String user="root";
	private String pwd = "";
	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	//加载驱动
	static{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	private void getConnection(){
		if(conn==null){
			try {
				conn = DriverManager.getConnection(url, user, pwd);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public ResultSet executeQuery(String query,
						List<Object> params){
		getConnection();
		try {
			//创建命令执行对象
			pstmt = conn.prepareStatement(query);
			//执行
			if(params!=null && params.size()>0){
				for(int i=0;i<params.size();i++){
					pstmt.setObject(i+1, params.get(i));
				}
			}
			rs=pstmt.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	
	public int executeUpdate(String update,
			List<Object> params){
		int result = 0;
		getConnection();
		try {
			pstmt = conn.prepareStatement(update);
			//执行
			if(params!=null && params.size()>0){
				for(int i=0;i<params.size();i++){
					pstmt.setObject(i+1, params.get(i));
				}
			}
			result = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			//关闭资源
			this.close();
		}
		return result;
	}
	/**
	 * 释放资源
	 */
	public void close(){
		try {
			if(rs!=null){
				rs.close();
				rs =null;
			}
			if(pstmt!=null){
				pstmt.close();
				pstmt=null;
			}
			if(conn!=null){
				conn.close();
				conn=null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
